package com.car.screenprojection;

import android.os.Environment;
import android.util.Log;


import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * socket客户端
 * Created by yuanyi on 2020/5/30.
 */
public class ClientConnector {

    private Socket mClient;
    /**
     * 服务端的ip
     */
    private String mDstName;
    /**
     * 服务端端口号
     */
    private int mDesPort;

    private ConnectLinstener mListener;


    public ClientConnector(String dstName, int dstPort) {
        this.mDstName = dstName;
        this.mDesPort = dstPort;
    }

    /**
     * 与socket服务端进行连接
     *
     * @throws IOException
     */
    public void connect() {
        try {
            Log.e("connect===", mClient+"==="+mDstName+"==="+mDesPort);

            if (mClient == null) {
                Log.e("connect===1", mClient+"==="+mDstName+"==="+mDesPort);
                mClient = new Socket(mDstName, mDesPort);

//                auth(BaseApplication.rid);    //把设备id注册到socket服务端
//                mClient.getInetAddress().getHostAddress();
            }

            Log.e("connect===2", mClient+"==="+mDstName+"==="+mDesPort);

            //获取其他设备发送的数据
            InputStream inputStream = mClient.getInputStream();
//            byte[] buffer = new byte[1024];
//            int len = -1;
//            while ((len = inputStream.read(buffer)) != -1) {
//                String data = new String(buffer, 0, len);
//
//                Log.e("connect===3", data+"===");
//
//                //通过回调接口将获取到的数据推送出去
//                if (mListener != null) {
//                    mListener.onReceiveData(data);
//                }
//            }

//            byte[] inputByte = null;
//            int length = 0;
//            DataInputStream dis = null;
//            FileOutputStream fos = null;
//            try {
//                try {
//                    Log.e("connect===3", "开始接收数据...1");
//
//                    dis = new DataInputStream(inputStream);
//                    fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+ File.separator+"0CarControl/01.png"));
//                    inputByte = new byte[1024];
//                    Log.e("connect===4", "开始接收数据...2");
//                    while ((length = dis.read(inputByte, 0, inputByte.length)) > 0) {
////                        System.out.println(length);
//                        fos.write(inputByte, 0, length);
//                        fos.flush();
//                    }
//                    Log.e("connect===5", "完成接收");
//                } finally {
////                    if (fos != null) fos.close();
////                    if (dis != null) dis.close();
//                }
//            } catch (Exception e) {
//
//            }


        } catch (Exception e) {
            Log.e("connect===e", e+"===");
            e.printStackTrace();
        }


    }

    /**
     * 认证方法，这个方法是用来进行客户端一对一发送消息的
     * 在实际项目中进行即时通讯时都需要进行登录，这里就是
     * 模拟客户端的账号
     *
     * @param authName
     */
    public void auth(final String authName) throws IOException {

        new Thread(new Runnable(){
            @Override
            public void run() {

                try {
                    if (mClient != null) {
                        Log.e("auth===", mClient+"==="+authName);

                        //将客户端账号发送给服务端，让服务端保存
                        OutputStream outputStream = mClient.getOutputStream();
                        //模拟认证格式，以#开头
                        outputStream.write(("#" + authName).getBytes());


                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }).start();


    }

    /**
     * 将数据发送给指定的接收者
     *
     * @param receiver 信息接数者
     * @param data     需要发送的内容
     */
    public void send(final String receiver, final String data){

        new Thread(new Runnable(){
            @Override
            public void run() {

                try {
                    Log.e("send===", mClient+"==="+receiver+"==="+data+"===");

                    OutputStream outputStream = mClient.getOutputStream();
                    //模拟内容格式：receiver+  # + content

                    if("request".equals(data)){
                        outputStream.write((receiver + "#" + 1 + "@" + data).getBytes());
                    }else{
                        outputStream.write((receiver + "#" + data).getBytes());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }).start();


    }

    public void sendPic(final String receiver, final String file){

        new Thread(new Runnable(){
            @Override
            public void run() {

                int length = 0;
                byte[] sendBytes = null;
                DataOutputStream dos = null;
                FileInputStream fis = null;
                try {
                    Log.e("sendPic===", mClient+"==="+receiver+"==="+file+"===");

                    mClient = new Socket(mDstName, mDesPort);
                    OutputStream outputStream = mClient.getOutputStream();
                    //模拟内容格式：receiver+  # + content


//                    dos = new DataOutputStream(outputStream);

                    Log.e("sendPic===1", "==="+dos);

                    fis = new FileInputStream(new File(file));

                    Log.e("sendPic===2", "==="+fis);

                    sendBytes = new byte[1024];
                    int n=0;
                    while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
//                        dos.write(sendBytes, 0, length);
//                        dos.flush();

                        n++;
                        outputStream.write(sendBytes, 0, length);

                        Log.e("sendPic===3", n+"==="+length);
                    }

//                    Thread.sleep(3000);

//                    outputStream.flush();
//                    outputStream.write(new byte[1]);

                    Log.e("sendPic===4", n+"==="+fis);

                } catch (Exception e) {
                    Log.e("sendPic===e", "==="+e);
                    e.printStackTrace();
                } finally {

                    try {
                        if (fis != null) fis.close();
                        if (dos != null) dos.close();
                        if (mClient != null) mClient.close();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }


                }


            }
        }).start();


    }

    /**
     * 断开连接
     *
     * @throws IOException
     */
    public void disconnect() throws IOException {
        Log.e("disconnect===", mClient+"===");

        if (mClient != null) {
            mClient.close();
            mClient = null;
        }
    }

//    public void reconnect() throws IOException {
//        disconnect();
//
//        connect();
//    }

    public void setOnConnectLinstener(ConnectLinstener linstener) {
        this.mListener = linstener;
    }

    /**
     * 数据接收回调接口
     */
    public interface ConnectLinstener {
        void onReceiveData(String data);
    }
}
